<?php

namespace App\Console\Commands;

use App\Models\Category;
use App\Models\User;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\Facades\Image;

class ImageCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'image';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        Category::where('parent_id', '!=', 0)->chunk(50, function ($list) {
            try {
                foreach ($list as $item) {
                    $basename = basename($item->file_path);
                    $img = Image::make(public_path($item->file_path));
                    $file_size = $img->filesize();
                    if ($file_size / 1024 > 50) {
                        $img->resize(300, null, function ($constraint) {
                            $constraint->aspectRatio();
                        })->save(public_path('images/'. $basename));
                    } else {
                        $result = copy(public_path($item->file_path), public_path('images/' . $basename));
                        if (!$result)
                            \Log::error($item->id);
                    }
                    $item->file_path = $basename;
                    $item->save();
                }
            } catch (\Exception $e) {
                var_dump($item->id);
                var_dump($e->getMessage());
                exit;
            }

        });
    }
}
